package com.shop.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.CollectionUtils;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author song_
 */
public class ServerHandler extends ChannelInboundHandlerAdapter  {

    /**
     * 需定义为类变量，因为 监听时是new ServerHandler()
     */
    private static List<Channel> channels = new ArrayList<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Received...");
        ByteBuf in = (ByteBuf) msg;
        try {
            byte[] bytes = new byte[in.readableBytes()];
            in.readBytes(bytes);
            System.out.println(new String(bytes));
            if (CollectionUtils.isEmpty(channels)){
                return;
            }
            for(Channel channel : channels) {
                channel.writeAndFlush(Unpooled.wrappedBuffer("server response...".getBytes(Charset.defaultCharset())));
            }
        } finally {
            // todo 当有writ 数据时，会自动释放msg 不用手动释放
            //ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
        System.out.println("add a new channel , channels size is :"+channels.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("error....");
        cause.printStackTrace();
    }
}
